/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.flink.streaming.python.util.serialization;

import org.python.util.PythonObjectInputStream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;

/**
 * A generic serialization utility, which turns java objects into their serialization form as
 * byte arrays and vise versa.
 */
public class SerializationUtils {
	public static byte[] serializeObject(Object o) throws IOException {
		try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos)) {
			oos.writeObject(o);
			oos.flush();
			return baos.toByteArray();
		}
	}

	@SuppressWarnings("unchecked")
	public static <X> X deserializeObject(byte[] bytes) throws IOException, ClassNotFoundException {
		try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new SerialVersionOverridingPythonObjectInputStream(bais)) {
			return (X) ois.readObject();
		}
	}

	/**
	 * A {@link PythonObjectInputStream} that ignores SerialVersionUID mismatches.
	 *
	 * <p>Classes generated by Jython have a non-deterministic serialVersionUID, which can prevents deserialization of
	 * user-defined python function in a different JVM.
	 *
	 * <p>The serialVersionUID is calculated as a 64-bit hash of the class name, interface class names, methods, and fields.
	 * If a Python class inherits from a Java class, as in the case of Python UDFs, then a proxy wrapper class is created.
	 * Its name isconstructed using the following pattern:
	 * <b>{@code org.python.proxies.<module-name>$<UDF-class-name>$<number>}</b>.
	 * The {@code <number>} part is increased by one in runtime, for every job submission. This results in different IDs for
	 * each run for the same Python class.
	 */
	private static class SerialVersionOverridingPythonObjectInputStream extends PythonObjectInputStream {

		private SerialVersionOverridingPythonObjectInputStream(InputStream in) throws IOException {
			super(in);
		}

		protected ObjectStreamClass readClassDescriptor() throws ClassNotFoundException, IOException {
			ObjectStreamClass readClassDescriptor = super.readClassDescriptor(); // initially streams descriptor

			Class<?> localClass;
			try {
				localClass = resolveClass(readClassDescriptor);
			} catch (ClassNotFoundException e) {
				return readClassDescriptor;
			}

			ObjectStreamClass localClassDescriptor = ObjectStreamClass.lookup(localClass);
			if (localClassDescriptor != null) { // only if class implements serializable
				final long localSUID = localClassDescriptor.getSerialVersionUID();
				final long readSUID = readClassDescriptor.getSerialVersionUID();
				if (readSUID != localSUID) {
					// Overriding serialized class version mismatch
					readClassDescriptor = localClassDescriptor; // Use local class descriptor for deserialization
				}
			}
			return readClassDescriptor;
		}
	}
}
